package com.kaiwukj.android.ufamily.mvp.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.BaseSwipeBackActivity;
import com.kaiwukj.android.ufamily.app.constant.ExtraCons;
import com.kaiwukj.android.ufamily.di.component.DaggerRecycleVideoComponent;
import com.kaiwukj.android.ufamily.di.module.RecycleVideoModule;
import com.kaiwukj.android.ufamily.mvp.contract.RecycleVideoContract;
import com.kaiwukj.android.ufamily.mvp.http.entity.helper.DynamicCollection;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.CommentParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommentResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DynamicResult;
import com.kaiwukj.android.ufamily.mvp.presenter.RecycleVideoPresenter;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.RecycleVideoAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.widget.home.PopupWindowUtil;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.jzvd.JzvdStd;

import static com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt.NoteReport;
import static com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt.RecycleVideoPlayer;


/**
 * @author Charles
 * @date 2019/8/22.
 * description：Kaiwu
 */
@Route(path = RecycleVideoPlayer)
public class RecycleVideoActivity extends BaseSwipeBackActivity<RecycleVideoPresenter> implements RecycleVideoContract.View {
    @BindView(R.id.rv_video)
    RecyclerView rvVideo;
    @BindView(R.id.title)
    View title;
    @BindView(R.id.back)
    ImageView ivBack;
    @BindView(R.id.ll_report)
    LinearLayout llReport;

    @Autowired(name = ExtraCons.EXTRA_KEY_VIDEO_DATA)
    String dynamicResultString;

    @Autowired
    int noteId;

    private RecycleVideoAdapter recycleVideoAdapter;
    private PagerSnapHelper snapHelper;
    private int scrollPos = 0;
    private DynamicCollection data;
    private PopupWindowUtil popupWindowUtil;
    private LinearLayoutManager layoutManager;

    List<DynamicResult> dataList = new ArrayList<>();

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerRecycleVideoComponent
                .builder()
                .appComponent(appComponent)
                .recycleVideoModule(new RecycleVideoModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        initPopUtil();
        return R.layout.activity_recycle_video;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {

    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        data = new Gson().fromJson(dynamicResultString, DynamicCollection.class);

        ivBack.setOnClickListener(view -> finish());
        llReport.setOnClickListener(view ->
                ARouter.getInstance().build(NoteReport)
                        .withInt("noteId", data.getResults().get(scrollPos).getId())
                        .withString("nickName", data.getResults().get(scrollPos).getUserName())
                        .withString("noteContent", data.getResults().get(scrollPos).getDynamicContent()).navigation());
        QMUIStatusBarHelper.setStatusBarDarkMode(this);
        QMUIStatusBarHelper.translucent(this);

        initRecyclerView(data.getResults());
    }

    private void initPopUtil() {
        popupWindowUtil = new PopupWindowUtil(getApplicationContext());
        popupWindowUtil.setOnEditDoneListener(text -> {
            if (TextUtils.isEmpty(text)) {
                showMessage("请输入评论内容");
                return;
            }
           /* CommentOtherRequest commentOtherRequest = new CommentOtherRequest();
            commentOtherRequest.setComment(text);
            commentOtherRequest.setNoteId(noteId);*/
            CommentParams params = new CommentParams();
            params.setCommentContent(text);
            params.setDynamicId(noteId);
            mPresenter.requestCommentOther(params);
        });
    }

    void initRecyclerView(List<DynamicResult> datas) {
        int position = 0;
        dataList = new ArrayList<>();
//        筛选有视频的帖子
        for (int i = 0; i < datas.size(); i++) {
            if (!TextUtils.isEmpty(datas.get(i).getVideo())) {
                dataList.add(datas.get(i));
            }
        }
//        找出当前视频的帖子位置
        for (int i = 0; i < dataList.size(); i++) {
            if (noteId == dataList.get(i).getId()) {
                position = i;
            }
        }
        recycleVideoAdapter = new RecycleVideoAdapter(this);
        layoutManager = new LinearLayoutManager(this);
        rvVideo.setLayoutManager(layoutManager);
        rvVideo.setAdapter(recycleVideoAdapter);
//        滚动到相应位置
        rvVideo.scrollToPosition(position);
        recycleVideoAdapter.setDatas(dataList);
        recycleVideoAdapter.setOnClickListener(new RecycleVideoAdapter.OnClickListener() {
            @Override
            public void OnLikeListener(int pos, boolean isLike) {
                if (isLike) {
                    mPresenter.postLikeCancel(noteId);
                } else {
                    mPresenter.postLike(noteId);
                }
            }

            @Override
            public void OnCommentListener(int pos) {
                mPresenter.requestCommentList(noteId, 0);
            }

            @Override
            public void OnTransmitListener(int pos) {

            }

            @Override
            public void OnFocusListener(int pos) {

            }

            @Override
            public void OnSendCommentListener(int pos, String text) {
                if (TextUtils.isEmpty(text)) {
                    showMessage("请输入评论内容");
                    return;
                }
                /*CommentOtherRequest commentOtherRequest = new CommentOtherRequest();
                commentOtherRequest.setComment(text);
                commentOtherRequest.setNoteId(noteId);*/
                CommentParams params = new CommentParams();
                params.setCommentContent(text);
                params.setDynamicId(noteId);
                mPresenter.requestCommentOther(params);
            }

            @Override
            public void OnHeadListener(int pos) {
                /*ARouter.getInstance().build(SocialCircleUrl).withInt(ExtraCons.EXTRA_KEY_ORDER_MINE_INDEX, 0)
                        .withString(SocialCircleActivity.FRAGMENT_KEY, SocialCirclePersonPageFragment.SOCIAL_CIRCLE_PERSON_PAGE_FRAGMENT)
                        .withInt(ExtraCons.EXTRA_KEY_USER_ID, datas.get(pos).getUserId()).navigation();*/
            }
        });

        snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(rvVideo);

        rvVideo.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE://停止滚动
                        View view = snapHelper.findSnapView(layoutManager);
                        RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);
                        if (viewHolder != null && viewHolder instanceof RecycleVideoAdapter.RecycleVideoHolder && viewHolder.getLayoutPosition() != scrollPos) {
                            JzvdStd.releaseAllVideos();
                            scrollPos = viewHolder.getLayoutPosition();
                            ((RecycleVideoAdapter.RecycleVideoHolder) viewHolder).video.startVideo();
                            noteId = dataList.get(scrollPos).getId();
                        }
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING://拖动
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动
                        break;
                }
            }
        });
    }

    @Override
    public Context getCtx() {
        return this;
    }

    @Override
    public void LikeSuccess() {
        showMessage("点赞成功");
    }

    @Override
    public void LikeCancelSuccess() {
        showMessage("取消成功");
    }

    @Override
    public void getCommentList(List<CommentResult> data) {
        popupWindowUtil.createCommentPop(RecycleVideoActivity.this,
                data, dataList.get(scrollPos).getCommentNum()).showBottom(R.layout.activity_recycle_video);
    }

    @Override
    public void commentSuccess() {
        View view = snapHelper.findSnapView(layoutManager);
        RecyclerView.ViewHolder viewHolder = rvVideo.getChildViewHolder(view);
        ((RecycleVideoAdapter.RecycleVideoHolder) viewHolder).tvCommentNum.setText(dataList.get(viewHolder.getLayoutPosition()).getCommentNum() + 1 + "");
    }

    /*@Override
    public void showMessage(@NonNull String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }*/

    @Override
    public void post(Runnable runnable) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        JzvdStd.releaseAllVideos();
    }
}
